function getUrlParam(paramName) {
            var reg = new RegExp("(^|&)" + paramName + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
            var r = window.location.search.substr(1).match(reg);  //匹配目标参数
            if (r != null) return unescape(r[2]); return null; //返回参数值
}


function initTable(e){
	var queryType = $("#queryType").val(); 
	var dataSourceCode = $("#dataSourceCode").val();
	if(!queryType == 1 || !dataSourceCode){
	  return; 
	}
	$.ajax({
		url  : URL.FRAMEWORK + "/autoGridConfig/queryTable",
		data :{"dataSourceCode":dataSourceCode},
		success : function(response){
			var data = response.data;
			if(!data){return;}
			var options = "<option value=''>请选择</option>";
			for(var i = 0 ; i < data.length ;i++){
				 options += "<option value='" + data[i] + "'>" + data[i] +  "</option>"
			}
			  $("#tableName").empty().append(options); 
		      $('#tableName').selectpicker('render');
		      $('#tableName').selectpicker('refresh'); 
		}
	})
}

function analysisSql(){   
	var validate = {require:true};
    var f = $("#querySql").easysingle(validate);
    var i = $("#querySql").valdate(validate);
	if(!$("#queryType").valdate(validate)){
		return;
	}
	var queryType = $("#queryType").val();
	if(queryType == 1){ 
		 if(!$("#dataSourceCode").valdate(validate) || !$("#tableName").valdate(validate)){
			 return ;
		 };
		;
	}else if(queryType == 2){
		 if(!$("#querySql").valdate(validate)){
			 return ;
		 }; 
	} 
	var dataSourceCode = $("#dataSourceCode").val();
	var tableName = $("#tableName").val();
    var querySql  = $("#querySql").val();
	$.ajax({
		data  : {queryType:queryType,"dataSourceCode":dataSourceCode,"tableName":tableName,querySql:querySql},
		url   : URL.FRAMEWORK + "/autoGridConfig/queryGridColumn",
	    success:function(response){ 
	    	var data = response.data;
	    	for(var i = 0; i < data.length ; i++ ){
	    		var record = data[i];
	    		record.elementType = "text";
	    		record.isDisplay   = 2;
	    		record.align       = 2;
	    		record.sort = i; 
	    		record.sqlSort = 0; 
	    		record.webSort = 0;
	    		record.isFixedQuery = 0;
	    		record.isDepthQuery = 0;
	    		record.width = "";
	    		record.dictCode = "";
	    		record.formatter = "";
	    		record.displaySort = "";  
	    	}
	    	var gridData = $("#autoGridConfig").bootstrapTable("getData"); 
	    	getAnalysisData(data,gridData); 
	    	$("#autoGridConfig").bootstrapTable('load', data); 
	    }
	})  
}

//新增的字段 以数据库为准 修改的字段以表格为准
function getAnalysisData(loadData,gridData){
	if(!gridData){
		return gridData;
	}	
	  for(var i = 0 ; i < loadData.length ; i++){
		var loadColumn = loadData[i].tableColumn; 
		 var flag = true;
		 for(var j = 0 ; j < gridData.length ;j++){
			 var gridColumn =   gridData[j].tableColumn;  
			 if(loadColumn == gridColumn){
				 loadData[i] = gridData[j];
				 flag = false;
			 } 
		}
	   if(flag){
		   gridData.push[loadData[i]]; 
	   }
	} 
	 return gridData;
}


function saveAutoGridConfig(){ 
   var form =  $("#autoFormConfig");
   var flag = form.selfform("validate"); 
   if(!flag){return flag ;}  
   var formData = form.selfform("getData");
   if(formData.webResourceCode){
	   formData.webResourceCode = JSON.stringify(formData.webResourceCode.split(",")); 
   } 
   var quickResourceForm = $("#quickResourceForm");
   var qrFormData = quickResourceForm.selfform("getData"); 
   if(qrFormData.roleIds){
	   qrFormData.roleIds  = qrFormData.roleIds.split(","); 
   }
  
   var gridData = $("#autoGridConfig").bootstrapTable("getData"); 
	$.ajax({
	   url   : URL.FRAMEWORK + "/autoGridConfig/save",
	   type :"post",
	   contentType:"application/json",
	   data : JSON.stringify({"grid":formData,"details":gridData,"quickResource":qrFormData}),
	   success:function(response){  
			 window.top.toastr.success("成功");
	   }
	})  
}



function initFormConfig(response){

	var dataSources = response.dataSources; 
	var dictionarys = $.dictionaryUtil.formatArray(response.dictionarys);
	var grid = response.grid.grid;
	var tables = response.tables;
	var tableJson = [];
	if(tables){
		for(var i = 0 ; i< tables.length ;i++){
			tableJson.push({value:tables[i],text:tables[i]});
		}
	}
	var operation = grid.webResourceCode ? JSON.parse(grid.webResourceCode) : [];
    var autoFormConfig =
     { 
        lableWidth   :  150,
		elementWidth :  200,
		models : [
			 {field:"id",lable:"ID",type:"hidden",value:grid.id}, 
			 {field:"name",lable:"名称",type:"text",value:grid.name,options:{validate:{require: true}}}, 
			 {field:"code",lable:"表格编码",type:"text",value:grid.code,options:{validate:{require: true}}},

			 {field:"queryType",lable:"自定义sql",type:"select",value:grid.queryType,
			  options:{data:dictionarys['grid_query_type'],validate:{require: true},
				  events:[{event:"click",method:initTable,param:{dateFmt:'yyyy-MM-dd HH:mm:ss',alwaysUseStartDate:true}}]
				}
			 }, 
			 {field:"dataSourceCode",lable:"数据源",type:"select",value:grid.dataSourceCode,
			  options:{data:dataSources,key:"code",value:"name",validate:{require:true},
				  events:[{event:"click",method:initTable,param:{dateFmt:'yyyy-MM-dd HH:mm:ss',alwaysUseStartDate:true}}]
				}
			 },  
			{field:"tableName",lable:"表",type:"select",search:true,value:grid.tableName,
				options:{data:tableJson,key:"value",value:"text"}
			 }, 
			{field:"isPage",lable:"是否分页",type:"radio",value:grid.isPage,
				 options:{data:dictionarys['grid_is_paging']}
			 },  
			 
			 {field:"webResourceCode",lable:"操作",type:"select",multiple:true,value:operation,
				 options:{data:dictionarys['grid_operation']}
			 },  
			 
		    {field:"selectType",lable:"选中方式",type:"radio",value:grid.selectType,
				 options:{data:dictionarys['grid_select_type']}
			 },
			 {field:"isInitQuery",lable:"是否初始化",type:"radio",value:grid.isInitQuery,
				 options:{data:dictionarys['grid_is_init_query']}
			 },
			 {field:"isLineNumber",lable:"是否显示行号",type:"radio",value:grid.isLineNumber,
				 options:{data:dictionarys['grid_is_row_number']}
			 }, 
			 {field:"pageSize",lable:"每页数量",type:"select",value:grid.pageSize,
				 options:{data:dictionarys['grid_page_size']}
			 }, 
 			 {field:"querySql",lable:"SQL",type:"textarea",value:grid.querySql,placeholder:
 				 "表关联时，使用到相同字段(列、查询条件)查询时不能给表另起别名，应使用表名代替别名. 如 select table_one.a ,table_two.a from table_one,table_two where table_one.a=table_two.a "},
/*			 {field:"myDate",lable:"时间",type:"date",
				   options:{events:[{event:"click",method:WdatePicker,param:{dateFmt:'yyyy-MM-dd HH:mm:ss',alwaysUseStartDate:true}}]}
			 }, */ 

		   ],
       }
    $("#autoFormConfig").selfform(autoFormConfig); 
}

function initQuickResourceForm(response){
	var quickResource = response.quickResource;
	var systems =  quickResource.systems;
	var resources = quickResource.resources;
	var roles =  quickResource.roles; 
    var quickResourceForm =
    { 
       lableWidth   :  150,
		elementWidth :  200,
		models : [
			 {field:"systemCode",lable:"所属系统",type:"select",value:quickResource.systemCode,
				  options:{data:systems,key:"code",value:"name", validate:{require:true}
				 }
			 }, 
 			{field:"resourcePid",lable:"父菜单",type:"select",search:true,value:quickResource.resourcePid,
 				options:{data:resources,key:"id",value:"name", validate:{require:true}}
 			 }, 
  			{field:"resourceName",lable:"菜单名",type:"text",value:quickResource.resourceName,
 				 options:{validate:{require:true}}
  			 }, 
   			{field:"roleIds",lable:"角色",type:"select",search:true,multiple:true,value:quickResource.roleIds,
   				options:{data:roles,key:"id",value:"name", validate:{require:true}}
   			 }, 
		]
    }
    $("#quickResourceForm").selfform(quickResourceForm);
	
}

function initGridConfig(config,data){ 
	if(data){
		for(var i= 0 ,len = data.length; i < len ; i++){
			data[i].uniqueId = data[i].id;
		}
	}
	var property =		
		{ 
		   sourceCode  : "dictCode",
	       sourceKey   : "dictKey", 
		   sourceValue : "dictValue", 
		   targetKey   : "value",
		   targetValue : "text"
		 } ; 
	var dictList = $.dictionaryUtil.formatArray(config.dictionarys,property);
	var dictMap =  $.dictionaryUtil.formatMap(config.dictionarys,property);
    var gridConfig = 
        {  
	        pagination: true,
	        pageSize : 1000,
	        clickToSelect: true,
	        idField: "uniqueId", 
	        uniqueId:"uniqueId",
	        data:data,
			columns :
				[
					 {checkbox: true },  
					 {title : "ID", field : "id",visible:false} ,
					 {title : "uniqueId", field : "uniqueId",visible:false} , 
					 {title : "字段", field : "tableColumn",editable: 
					   {
			                type: 'text',
			                title: '字段',
			                validate: function (v) {
			                    if (!v) return '字段不能为空';
			                }
			            }
					 } ,
					 {title : "字段别名", field : "columnAlias",editable: 
					   {
			                type: 'text',
			                title: '字段别名',
			                validate: function (v) {
			                    if (!v) return '字段别名不能为空';
			                }
			            }
					 } ,
					 {title : "表名/表别名", field : "tableName",editable: 
					   {
			                type: 'text',
			                title: '表名',
			                validate: function (v) {
			                    if (!v) return '表名不能为空';
			                }
			            }
					 } ,
					 {title : "名称", field : "name",editable: 
					   {
			                type: 'text',
			                title: '名称',
			                validate: function (v) {
			                    if (!v) return '名称不能为空';
			                }
			            }
					 } ,
					 {title : "数据类型", field : "dataType", editable:
				        {
		            	    type:  "select",
		            	    title: '数据类型',
			                source: function(){
			                	return dictList["grid_detail_data_type"];
			                }
			            }
					 } ,  
					 {title : "元素类型", field : "elementType",   editable:
					        {
			            	    type:  "select",
			            	    title: '数据类型',
				                source: function(){
				                	return dictList["grid_detail_element_type"];
				                }
				            } 
		        	  } ,  
		    		 {title : "宽度", field : "width",editable: 
					   {
			                type: 'text',
			                title: '宽度' 
			            }},
					 {title : "字典编码", field : "dictCode",editable: 
					   {
			                type: 'text',
			                title: '字典编码', 
			            }} ,
					 {title : "格式化", field : "formatter",editable: 
					   {
			                type: 'text',
			                title: '格式化' 
			            }} ,
					 {title : "排序", field : "sort",editable: 
					   {
			                type: 'text',
			                title: '排序' 
			            }} ,
					 {title : "显示", field : "isDisplay",value:1, editable: 
						   {
				                type: 'select',
				                title: '显示',
				                source: function (v) {
				                     return dictList["grid_detail_is_display"];
				                }
				            } 
					   } , 
					 {title : "对齐", field : "align",value:2,
						   editable: 
						   {
				                type: 'select',
				                title: '对齐',
				                source: function (v) {
				                     return dictList["grid_detail_align"];
				                }
				            }
					   } ,
			 
					   {title : "sql排序", field : "sqlSort",value:0,
						   editable: 
						   {
				                type: 'select',
				                title: 'sql排序方式',
				                source: function (v) {
				                     return dictList["grid_detail_sort_by"];
				                }
				            }  
					   } , 
					   {title : "web排序", field : "webSort",value:0,
						   
						   editable: 
						   {
				                type: 'select',
				                title: 'web排序方式',
				                source: function (v) {
				                     return dictList["grid_detail_sort_by"];
				                }
				            }  
					   } ,
					   
					   
					   {title : "固定查询", field : "isFixedQuery",value:0,
						   editable: 
						   {
				                type: 'select',
				                title: '固定查询',
				                source: function (v) {
				                     return dictList["grid_detail_is_fixed_query"];
				                }
				            } 
					   } ,
					   {title : "高级查询", field : "isDepthQuery",value:0,
						   
						   editable: 
						   {
				                type: 'select',
				                title: '高级查询',
				                source: function (v) {
				                     return dictList["grid_detail_is_depth_query"];
				                }
				            }  
					   }
			
			    ] 
		 };
  $("#autoGridConfig").bootstrapTable(gridConfig); 
}
 

function initEvent(){
	$('#dataSourceCode,#queryType').on('changed.bs.select',initTable);
	
	$(document).on("click","#analysisSql",analysisSql)
	
	$("#saveAutoGridConfig").on("click",saveAutoGridConfig)
}

$(function(){
	var gridCode  = getUrlParam("gridCode");
	$.ajax({
		url: URL.FRAMEWORK + "/autoGridConfig/queryConfig?gridCode="+gridCode,
	    success:function(response){ 
	    	var data = response.data;
	    	initFormConfig(data);
	    	initQuickResourceForm(data);
	    	initGridConfig(data,data.grid.details);
	    	initEvent(); 
	    }
	}) 
});
 

  